using UnityEngine;
using System.Collections;
using Entities;

public class MobAI : MonoBehaviour {
	
	private Fighter target;
	private Mob mob;
	private CharacterController controller;
	private Material indicator;

	// Use this for initialization
	void Start () {
		target = null;
		mob = Mobs.Instance.getMob(gameObject);
		mob.currentAction = new IdleAction();
		controller = (CharacterController) GetComponent("CharacterController");
		
		indicator = gameObject.transform.GetChild(0).renderer.material;
	}
	
	// Update is called once per frame
	void Update () {
		foreach(GameObject obj in GameObject.FindGameObjectsWithTag("Player")){
			mob.getMobGroup().addEnemy(Players.Instance.getPlayer(obj));
		}
		
		target = mob.chooseTarget();
		
		if (target != null) {
			mob.currentAction = mob.currentAction.nextAction(mob, target);
		}
		
		
		Debug.Log (mob.currentAction.type);
		
		switch(mob.currentAction.type){
			case TypeAction.attack : attack () ; break ;	
			case TypeAction.follow : follow () ; break ;	
			case TypeAction.back : back () ; break ;	
			case TypeAction.chase : chase () ; break ;	
			case TypeAction.clear : clear ((mob.currentAction as ClearAction).other) ; break ;	
			case TypeAction.idle : idle() ; break ;
		}
		
	}
	
	private void move(Vector3 targetPos){
		Vector3 dir = targetPos - transform.position;
        dir.y = 0; // keep only the horizontal direction
		dir.Normalize();
		
		//Vector3 position = new Vector3(transform.position.x, 0 , transform.position.z);
	    controller.SimpleMove(dir * (float)mob.getMovementSpeed());
		
		transform.localRotation = Quaternion.LookRotation(dir);
	}
	
	private void moveAway(Vector3 targetPos){
		Vector3 dir = transform.position - targetPos;
        dir.y = 0; // keep only the horizontal direction
		dir.Normalize();
		
		//Vector3 position = new Vector3(transform.position.x, 0 , transform.position.z);
	    controller.SimpleMove(dir * (float)mob.getMovementSpeed());
		
		transform.localRotation = Quaternion.LookRotation(dir);
	}
	
	private void back() {
		Vector3 targetPos = mob.getMobGroup().getStartingPosition();
		move(targetPos);
		indicator.color = Color.green;
	}
	
	private void attack(){
		//use skill	
		indicator.color = Color.red;
	}
	
	private void chase(){
		Vector3 targetPos = target.getGameObject().transform.position;
		move(targetPos);
		indicator.color = Color.yellow;
	}
	
	private void follow(){
		Vector3 targetPos = mob.getLeader().getGameObject().transform.position;
		move(targetPos);
		indicator.color = Color.blue;
	}
	
	private void clear(Mob mob){
		Vector3 targetPos = mob.getGameObject().transform.position;
		moveAway(targetPos);
		indicator.color = Color.black;
	}
	
	private void idle(){
		//idle
		indicator.color = Color.white;
	}
}
